<template>
  <el-dialog
    :title="'Add Expense Account'"
    :visible.sync="dialogVisible"
    width="100%"
    :fullscreen="true"
    :before-close="handleClose"
    :destroy-on-close="true">
    <div class="xlSeeFrom">

      <div class="tab-item">
        <!--报销单说明-->
        <div class="item">
          <p class="tab-title">Expense Account Description</p>
          <div class="tab">
            <table>
              <tr>
                <td>Expense Account ID</td>
                <td>Expense Account Name<span style="color:red;font-size:16px;">*</span></td>
                <td>Applicant</td>
                <td>Project<span style="color:red;font-size:16px;">*</span></td>
              </tr>
              <tr>
                <td>{{addForm.expense_id}}</td>
                <td><el-input v-model="addForm.expense_name" placeholder="please expense account name"></el-input></td>
                <td>{{pe_name}}</td>
                <td>
                  <el-select v-model="addForm.expense_project_name" @focus="clickProjectSelect" placeholder="please select project" style="width:100%">
                    <el-option
                      v-for="item in options"
                      :key="item.project_id"
                      :value="item.project_name"
                      :label="item.project_name">
                    </el-option>
                  </el-select>
                </td>
              </tr>
              <tr>
                <td>Type<span style="color:red;font-size:16px;">*</span></td>
                <td>Date<span style="color:red;font-size:16px;">*</span></td>
                <td>Day Number</td>
                <td>Submit Time</td>
              </tr>
              <tr>
                <td>
                    <el-select v-model="addForm.expense_type" placeholder="please select expense account type" style="width:100%">
                      <el-option label="Travel" value="Travel"></el-option>
                      <el-option label="Team building" value="Team building"></el-option>
                      <el-option label="Training" value="Training"></el-option>
                      <el-option label="Bonus" value="Bonus"></el-option>
                      <el-option label="Purchase" value="Purchase"></el-option>
                      <el-option label="Traffic in the city" value="Traffic in the city"></el-option>
                      <el-option label="Other" value="other"></el-option>
                  </el-select>
                </td>
                <td>
                  <span class="block">
                    <el-date-picker
                      v-model="addForm.expense_start_time"
                      type="datetime"
                      placeholder="start time"
                      format="yyyy-MM-dd HH:mm"
                      value-format='yyyy-MM-dd HH:mm'
                      @change='selectDate'
                      :picker-options="pickerOptionsStart"
                      style="width:50%">
                    </el-date-picker>
                  </span>
                  <span class="block">
                    <el-date-picker
                      v-model="addForm.expense_end_time"
                      type="datetime"
                      placeholder="end time"
                      format="yyyy-MM-dd HH:mm"
                      value-format='yyyy-MM-dd HH:mm'
                      @change='selectDate'
                      :picker-options="pickerOptionsEnd"
                      style="width:50%">
                    </el-date-picker>
                  </span>
                </td>
                <td>{{addForm.expense_days}}</td>
                <td>{{addForm.expense_submit_time}}</td>
              </tr>
              <tr>
                <td>Tax Rate<span style="color:red;font-size:16px;">*</span></td>
                <td>Payment Currency<span style="color:red;font-size:16px;">*</span></td>
                <td>Amount(after tax rate)</td>
                <td>exchange rate of payment currrncy to UAH<span style="color:red;font-size:16px;">*</span></td>
              </tr>
              <tr>
                <td>
                  <el-input-number v-model="addForm.expense_pe_tax_rate" :precision="2" :step="0.1" :min="0" :max="1" @change="onTaxRateInputBlur"></el-input-number>
                </td>
                <td>
                  <el-select v-model="addForm.expense_payment_currency" placeholder="please select paymeny currency" style="width:100%">
                    <el-option label="UAH" value="UAH"></el-option>
                    <el-option label="CNY" value="CNY"></el-option>
                    <el-option label="USD" value="USD"></el-option>
                    <el-option label="EUR" value="EUR"></el-option>
                  </el-select>
                </td>
                <td>{{addForm.total_amount.toFixed(2)}}{{addForm.expense_payment_currency}}</td>
              <td>
                <el-input-number v-model="addForm.payment_to_uah" :precision="2" placeholder="please enter exchange rate of payment currrncy to UAH" :step="0.1" :min="0" :max="10"></el-input-number>
              </td>
              </tr>
            </table>
          </div>
        </div>

        <!--报销单明细-->
        <div>
          <div class="tit-header">
            <div class="item">
              <p class="tab-title">Expense Account Details</p>
            </div>
            <div class="item">
              <el-button type="primary" @click="addRow()">add detail</el-button>
              <el-button type="primary" @click="delData()">delete details selected</el-button>
            </div>
          </div>

          <div class="tab">
            <el-table
              :header-cell-style="{background:'#F2F6FC',color:'#606266'}"
              :data="tableData"
              ref="table"
              :row-class-name="rowClassName"
              height="400px"
              tooltip-effect="dark"
              border
              style="width:100%"
              @selection-change='selectRow'>
              <el-table-column type="selection" width="45" align="center"></el-table-column>
              <el-table-column label="S/N" type="index" width="60" align="center"></el-table-column>
              <el-table-column label="Type" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.expense_type" placeholder="please select detail type" style="width:100%">
                    <el-option label="Air tickets" value="Air tickets"></el-option>
                    <el-option label="Hotel" value="Hotel"></el-option>
                    <el-option label="Taxi" value="Taxi"></el-option>
                    <el-option label="Train ticket" value="Train ticket"></el-option>
                    <el-option label="Travel allowance" value="Travel allowance"></el-option>
                    <el-option label="Team building" value="Team building"></el-option>
                    <el-option label="Lecturer fee" value="Lecturer fee"></el-option>
                    <el-option label="Purchase" value="Purchase"></el-option>
                    <el-option label="Bones" value="Bones"></el-option>
                    <el-option label="Other" value="Other"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="Invoice Currency" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.invoice_currency" placeholder="please select invoice currency" style="width:100%">
                    <el-option label="UAH" value="UAH"></el-option>
                    <el-option label="CNY" value="CNY"></el-option>
                    <el-option label="USD" value="USD"></el-option>
                    <el-option label="EUR" value="EUR"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="exchange rate of invoice currency to payment currency" align="center">
                <template slot-scope="scope">
<!--                  <el-input type="number" v-model="scope.row.exchange_rate" placeholder="please enter exchage rate" @blur="onDetailRateInputBlur"></el-input>-->
                  <el-input-number v-model="scope.row.exchange_rate" :precision="2"  :step="0.1" :min="0" :max="10" @blur="onDetailRateInputBlur" @change="onDetailRateInputBlur"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="Detail Amount" align="center">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.expense_amount" :precision="2"  :step="1" :min="0" @blur="onDetailAmountInputBlur" @change="amount($event)"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="upload invoice attachment(only one and only pdf)" align="center">
                <template slot-scope="scope">
                    <el-upload
                      class="upload-demo"
                      action="string"
                      :limit="1"
                      accept=".pdf"
                      :on-remove="(file, fileList) => (deleteFile(file, fileList,scope.row.detail_id))"
                      :headers="headers"
                      :before-upload="beforeUpload"
                      :http-request="(e)=>(uploadFile(e,scope.row.detail_id))">
                      <el-button size="small" type="primary">upload</el-button>
                    </el-upload>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

      </div>

    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">Close</el-button>
      <el-button type="primary" @click="saveMyReimbursement">Save</el-button>
      <el-button type="success" @click="createMyReimbursement" :loading="loading">Submit</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {createMyReimbursement,addMyReimbursementDetail,deleteMyReimbursementDetail,addMyReimbursement,deleteFile} from '@/request/other_api'
import { getProjectAddedList} from "@/request/api";
import axios from 'axios'

export default {
  data(){
    return {
      dialogVisible:false,
      loading:false,
      contract_currency:"",
      //报销单说明表单中的数据
      addForm:{
        expense_id:'',
        expense_name:'',
        expense_username:'',
        expense_project_name:'',
        expense_start_time:'',
        expense_end_time:'',
        expense_submit_time:'',
        expense_pe_tax_rate:'',
        expense_type:'',
        expense_payment_currency:'',
        expense_days:'',
        total_amount:0,
        payment_to_uah:'',
      },
      pickerOptionsStart: {
        disabledDate: time => {
          if (this.addForm.expense_end_time) {
                return time.getTime() > new Date(this.addForm.expense_end_time).getTime()
          }
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          if (this.addForm.expense_start_time) {
                return time.getTime() < new Date(this.addForm.expense_start_time).getTime()
          }
        }
      },
      status:0,
      pe_name:'',
      tableData:[],
      options: [],
      selectlistRow: [],
      headers:{'Content-Type':'multipart/form-data'}
    }
  },
  mounted () {
    this.level = sessionStorage.getItem('level')
  },
  methods:{
    amount(e){
      this.computeTotalAmount()
    },
    beforeUpload(file){
      var type = file.name
      type = type.split('.')[1]
      if(type != 'pdf'){
        this.$message({
          message: 'Upload files can only be in pdf format!',
          type: 'warning'
        });
        return false;
      }else {
        this.$message.success("Upload Succsee!")
      }
    },
    uploadFile(file,id) {
      let url="/api/finance/expense_file"
      let fd = new FormData();
      fd.append('invoice_attachment',file.file);
      fd.append('detail_id',id)
      axios({
        url:url,
			  data: fd,
        method:'post',
        }).then(res => {
        if(res.code === 200) {
          this.$message.success("Upload Succsee!")
        }
      })
    },
    deleteFile(file,fileList,id){
      deleteFile({
        detail_id:id
      }).then(res =>{
        if(res.code == 200){
          this.$message.success("Delete Success!")
        }
      })
    },
    // 新增时获取已有数据
    addMyReimbursement(){
      addMyReimbursement().then(res =>{
        if(res.code == 200){
          this.contract_currency = res.contract_currency

          this.addForm.expense_id = res.expense_id
          this.pe_name = res.pe_name
          this.addForm.expense_submit_time = res.submit_time
          this.addForm.expense_pe_tax_rate = res.tax_rate
          this.addForm.expense_username = res.username
          this.addForm.expense_payment_currency = res.payment_currency
        }else {
          this.$message.error(res.msg)
          this.dialogVisible = false
        }

      })
    },
    // 点击项目下拉框中从后端获取项目
    clickProjectSelect(){
      getProjectAddedList().then(res => {
        this.options = res.data
      })
    },
    // 选中结束时间后算出天数
    selectDate(){
      this.addForm.expense_days = 0;
      let startDateTime = this.addForm.expense_start_time;
      let endDateTime = this.addForm.expense_end_time;
      startDateTime = startDateTime.split(" ");
      endDateTime = endDateTime.split(" ");
      let startDate = startDateTime[0].split("-");
      let endDate = endDateTime[0].split("-");
      let startTime = startDateTime[1].split(":");
      let endTime = endDateTime[1].split(":");
      if(endDate[2] == startDate[2]) {
        if(endTime[0]-startTime[0]<=0){
          this.addForm.expense_end_time = ''
          return
        }
      }
      startDate = new Date(startDate[0],startDate[1],startDate[2]);
      endDate = new Date(endDate[0],endDate[1],endDate[2]);
      let days = parseInt(Math.abs(startDate  -  endDate)  /  1000  /  60  /  60  /  24) + 1;
      if(parseInt(startTime[0]) > 12) {
        days = days - 0.5
      };
      if(parseInt(endTime[0]) < 12) {
        days = days - 0.5
      };
      this.addForm.expense_days = days
    },
    // 序号
    rowClassName({ row, rowIndex }) {
      row.xh = rowIndex + 1;
    },
    // 获取明细表选中时的数据
    selectRow (val) {
      this.selectlistRow = val
    },
    // 增加明细表中行
    addRow () {
        var list = {
        expense_type:'',
        invoice_currency:this.contract_currency,
        exchange_rate:'',
        expense_amount:'',
        detail_id:'',
      };
      addMyReimbursementDetail({
        expense_id:this.addForm.expense_id
      }).then(res =>{
        list.detail_id = res.detail_id
      })
      this.tableData.push(list)
    },
    // 删除明细表选中行
    delData () {
      this.$confirm('Do you confirm delete?', 'message', {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          for (let i = 0; i < this.selectlistRow.length; i++) {
            let val = this.selectlistRow
            val.forEach((val, index) => {
              this.tableData.forEach((v, i) => {
                if (val.xh === v.xh) {
                  this.tableData.splice(i, 1)
                }
              })
            })
          }
        deleteMyReimbursementDetail({
          data:this.selectlistRow
        }).then(res =>{
          if (res.code == 200) {
            this.$message.success("Delete Success!")
          }
        })
        //删除完数据之后清除勾选框
        this.$refs.table.clearSelection()
        //删除后计算总金额
        this.computeTotalAmount()
        }).catch(() => {

        })

    },
    //离开明细金额输入框时计算金额
    onDetailAmountInputBlur(){
      this.computeTotalAmount()
    },
    //离开明细汇率输入框时计算金额
    onDetailRateInputBlur(){
      this.computeTotalAmount()
    },
    //离开报销说明税率输入框时计算金额
    onTaxRateInputBlur(){
      this.computeTotalAmount()
    },
    //计算总金额
    computeTotalAmount(){
      this.addForm.total_amount = 0
      for(let i = 0; i < this.tableData.length; i++){
        let amount = parseInt(this.tableData[i].expense_amount)
        let exchange_rate = parseFloat(this.tableData[i].exchange_rate)
        if(this.tableData[i].expense_amount === '') {
          amount = 0
        }
        if(this.tableData[i].exchange_rate === '') {
          exchange_rate = 0
        }
        this.addForm.total_amount = this.addForm.total_amount + amount * exchange_rate
      }
      this.addForm.total_amount = this.addForm.total_amount * (1-this.addForm.expense_pe_tax_rate)
      this.addForm.total_amount = Number(this.addForm.total_amount.toFixed(2))
    },
    //保存报销单
    saveMyReimbursement(){
      if(!this.addForm.expense_name){
        this.$message.error('Expense account name is empty')
        return
      }
      if(!this.addForm.expense_project_name){
        this.$message.error('Project is empty')
        return
      }
      if(!this.addForm.expense_start_time){
        this.$message.error('Start time is empty')
        return
      }
      if(!this.addForm.expense_end_time){
        this.$message.error('End time is empty')
        return
      }
      if (!this.addForm.expense_type) {
        this.$message.error('Expense account type is empty')
        return
      }
      if(!this.addForm.payment_to_uah) {
        this.$message.error('Exchange rate of payment currrncy to UAH is empty')
        return
      }
      // 报销明细不能为空限制
      for (let i = 0; i < this.tableData.length; i++) {
        if(!this.tableData[i].exchange_rate
        || !this.tableData[i].expense_amount
        || !this.tableData[i].expense_type
        || !this.tableData[i].invoice_currency) {
          this.$message.error('There are empty item in expense account details form')
          return
        }
      }
      createMyReimbursement({
      "data": {
          "explain":this.addForm,
          "detail":this.tableData
      }
      }).then(res => {
        if(res.code === 200){
          this.$message.success('Save Success!')
          this.dialogVisible = false
          this.$parent.getMyReimbursementList()
          this.clearData()
        }
      })
    },
    //提交报销单
    createMyReimbursement(){

      if(!this.addForm.expense_name){
        this.$message.error('Expense account name is empty')
        return
      }
      if(!this.addForm.expense_project_name){
        this.$message.error('Project is empty')
        return
      }
      if(!this.addForm.expense_start_time){
        this.$message.error('Start time is empty')
        return
      }
      if(!this.addForm.expense_end_time){
        this.$message.error('End time is empty')
        return
      }
      if (!this.addForm.expense_type) {
        this.$message.error('Expense account type is empty')
        return
      }
      if(!this.addForm.payment_to_uah) {
        this.$message.error('Exchange rate of payment currrncy to UAH is empty')
        return
      }
      if(this.tableData.length == 0){
        this.$message.error('The reimbursement details list cannot be empty!')
        return;
      }
      // 报销明细不能为空限制
      for (let i = 0; i < this.tableData.length; i++) {
        if(!this.tableData[i].exchange_rate
        || !this.tableData[i].expense_amount
        || !this.tableData[i].expense_type
        || !this.tableData[i].invoice_currency) {
          this.$message.error('There are empty item in expense account details form')
          return
        }
      }
      this.loading = true
      createMyReimbursement({
        commit:1,
        "data": {
           "explain":this.addForm,
           "detail":this.tableData
        }
      }).then(res => {
        if(res.code === 200){
          this.$message.success('Submit Success!')
          this.loading = false
          this.dialogVisible = false
          this.$parent.getMyReimbursementList()
          this.clearData()
        }else{
          this.loading = false
          this.$message.error('Submit Error!')
        }
      })
    },
    //关闭窗口
    handleClose (done) {
      this.dialogVisible = false
      this.clearData()
    },
    //清空数据
    clearData(){
      this.addForm.expense_name = ''
      this.addForm.expense_project_name = ''
      this.addForm.expense_type = ''
      this.addForm.expense_start_time = ''
      this.addForm.expense_end_time = ''
      this.addForm.expense_days = ''
      this.payment_to_uah = ''
      this.addForm.total_amount = 0
      this.tableData = []
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-form-item__label {
  background-color: #eee;
  text-align: center;
  //width: 121px;
}
/deep/ .el-dialog__header {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #eee;
}
/deep/ .el-dialog__body {
  padding: 10px 20px;
  color: #333;
  font-size: 15px;
  word-break: break-all;
}
.step{
  margin-bottom: 10px;
}
.content{
  margin-top: 10px;
  margin-bottom: 10px;

}
.tab-item{
  width: 100%;
  padding: 10px 0;
  border: 1px solid #eee;

  table{
    width: 100%;
    font-family: verdana,arial,sans-serif;
    font-size:14px;
    color:#333333;
    border-width: 1px;
    border-color: #999999;
    border-collapse: collapse;
  }
  table td{
    border-width: 1px;
    padding: 4px;
    border-style: solid;
    border-color: #999999;
    width: 25%;
  }
  table tr:nth-child(2n+1){
    background-color:#F2F6FC;
    height:50px;
    text-align: center;
  }
  table tr:nth-child(2n){
    background-color: #fff;
    height:50px;
    text-align: center;
  }

.tab-title{
  font-family: SourceHanSansSC;
  font-weight: 700;
  font-size: 20px;
  color: rgb(16, 16, 16);
  font-style: normal;
  letter-spacing: 0px;
  line-height: 30px;
  text-decoration: none;
  padding: 5px 10px;
}
/deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
  width: 100%;
 }
}

.tit-header{
display: flex;
justify-content: space-between;
margin: 10px 0;
}

</style>
